package com.bee.剑指offer;


/**
 * 输入：{2,5,1,9},5
 * 返回值：{2,1,9}
 * 说明：给定你链表中值为 5 的第二个节点，那么在调用了你的函数之后，该链表应变为 2 -> 1 -> 9
 */
public class 删除链表的节点 {

    public static ListNode deleteNode(ListNode head, int val) {
        if (head == null) {
            return null;
        }
        ListNode first = head;
        ListNode pre = null;
        while (first != null) {
            if (first == head && first.val == val) {
                head = first.next;
            }
            if (first.val == val && pre != null) {
                pre.next = first.next;
            }
            pre = first;
            first = first.next;

        }
        return head;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(2);
        head.next = new ListNode(5);
        head.next.next = new ListNode(1);
        head.next.next.next = new ListNode(9);
        ListNode listNode = deleteNode(head, 2);
        while (listNode != null) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }
}
